package com.example.exchangeapp.pxx;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.NetworkOnMainThreadException;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.exchangeapp.MainActivity;
import com.example.exchangeapp.R;
import com.example.exchangeapp.yy.constant.AppId;
import com.example.exchangeapp.yy.constant.AppSecret;
import com.example.exchangeapp.zjs.BaseResponse;
import com.example.exchangeapp.zjs.MySQLiteOpenHelper;
import com.example.exchangeapp.zjs.User;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ModifyActivity extends AppCompatActivity {

    private Button submit;
    private EditText userId;
    private EditText phone;
    private ImageView avater;
    private Button selectBtn;
    private final Gson gson = new Gson();
    private androidx.appcompat.widget.Toolbar toolbar;
    private File imageFile;
    private String avaterUrl;
    private String id;
    private String ph;
    private String avat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify);
        toolbar=findViewById(R.id.modify_toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        initView();
    }

    private void initView() {
        Bundle bundle=getIntent().getExtras();
        id=bundle.getString("id");
        ph=bundle.getString("phone");
        avat=bundle.getString("avatar");

        submit=findViewById(R.id.submit);

        userId=findViewById(R.id.userId);
        userId.setKeyListener(null);
        userId.setFocusable(false);
        userId.setFocusableInTouchMode(false);
        userId.setEnabled(false);
        userId.setText(id);
        userId.setTextColor(0xFF018786);

        phone=findViewById(R.id.phoneNumber);
        phone.setKeyListener(null);
        phone.setFocusable(false);
        phone.setFocusableInTouchMode(false);
        phone.setEnabled(false);
        phone.setText(ph);
        phone.setTextColor(0xFF018786);

        avater=findViewById(R.id.userImage);
        if(avat!=null){
            Glide.with(this).load(avat).into(avater);
        }

        selectBtn=findViewById(R.id.select);
        selectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 0);
            }
        });

        submit=findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openDialog("确认修改？","修改个人信息");
            }
        });
    }

    //弹出确认框
    private void openDialog(String strMsg, String strTitle){
        new AlertDialog.Builder(this)
                .setTitle(strTitle)
                .setMessage(strMsg)
                .setPositiveButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                Toast.makeText(ModifyActivity.this, "修改失败！", Toast.LENGTH_SHORT).show();
                            }
                        })
                .setNegativeButton("确认",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                if(imageFile!=null){
                                    post();
                                }
                    }
                })
                .show();
    }

    //打开相册
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 0 && resultCode == RESULT_OK) {
            // 获取选择的图片
            Uri imageUri = data.getData();
            // 显示图片
            avater.setImageURI(imageUri);
            // 获取图片文件对象
            imageFile = uriToFile(imageUri);
        }
    }

    // 将Uri转换成File对象
    private File uriToFile(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            String filePath = cursor.getString(column_index);
            cursor.close();
            return new File(filePath);
        }
        return null;
    }

    //上传头像的post请求和回调函数
    private void post(){
        new Thread(() -> {
            // url路径
            String url = "http://47.107.52.7:88/member/tran/image/upload";
            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", AppId.AppId)
                    .add("appSecret", AppSecret.appSecret)
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");

            MultipartBody multipartBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("fileList", imageFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, imageFile))
                    .build();

            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(multipartBody)
                    .build();

            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    private okhttp3.Callback callback = new okhttp3.Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response)
                throws IOException {
            if (response.isSuccessful()) {
                final String body = response.body().string();
                Type jsonType = new TypeToken<ResponseBody<ImageData>>(){}.getType();
                // 解析json串到自己封装的状态
                ResponseBody<ImageData> dataResponseBody = gson.fromJson(body,jsonType);
                avaterUrl=dataResponseBody.getData().getImageUrlList().get(0);
                post2();
            } else {
            }
        }
    };

    //修改信息的post请求和回调函数
    private void post2() {
        new Thread(() -> {
            // url路径
            String url = "http://47.107.52.7:88/member/tran/user/update";
            // 请求头
            Headers headers = new Headers.Builder()
                    .add("appId", AppId.AppId)
                    .add("appSecret", AppSecret.appSecret)
                    .add("Accept", "application/json, text/plain, */*")
                    .build();

            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("avatar", avaterUrl);
            bodyMap.put("userId", id);
            // 将Map转换为字符串类型加入请求体中
            String body = gson.toJson(bodyMap);
            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();

            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback1);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }
    private okhttp3.Callback callback1 = new okhttp3.Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response)
                throws IOException {
            String body = response.body().string();
            com.example.exchangeapp.zjs.BaseResponse dataResponseBody = gson.fromJson(body, BaseResponse.class);
            if (dataResponseBody.getCode() == 200) {
                User user = dataResponseBody.getData();

                //获取可写数据库
                MySQLiteOpenHelper mySQLiteHelper = new MySQLiteOpenHelper(ModifyActivity.this);
                SQLiteDatabase db = mySQLiteHelper.getWritableDatabase();

                // 定义要修改的字段和新值
                ContentValues values = new ContentValues();
                values.put("avatar", avaterUrl);

                // 执行更新操作
                String whereClause = "id=?";
                String[] whereArgs = new String[]{id};
                int rowsUpdated = db.update("Users", values, whereClause, whereArgs);

                // 检查更新是否成功
                if (rowsUpdated > 0) {
                    Log.d("ModifyActivity", "Update successful");
                } else {
                    Log.d("ModifyActivity", "No rows updated");
                }
                // 关闭数据库连接
                db.close();
                //修改成功
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(ModifyActivity.this, "修改成功！", Toast.LENGTH_SHORT).show();
                    }
                });
                Intent intent=new Intent(ModifyActivity.this,MainActivity.class);
                startActivity(intent);
            } else {
            }
        }
    };

}

/**
 * http响应体的封装协议
 */
class ResponseBody <T>{

    /**
     * 业务响应码
     */
    private int code;
    /**
     * 响应提示信息
     */
    private String msg;
    /**
     * 响应数据
     */
    private T data;

    public ResponseBody(){}

    public int getCode() {
        return code;
    }
    public String getMsg() {
        return msg;
    }
    public T getData() {
        return data;
    }

    @NonNull
    @Override
    public String toString() {
        return "ResponseBody{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}

class ImageData{
    private Long imageCode;
    private List<String> imageUrlList;

    public ImageData() {
    }

    public Long getImageCode() {
        return imageCode;
    }

    public void setImageCode(Long imageCode) {
        this.imageCode = imageCode;
    }

    public List<String> getImageUrlList() {
        return imageUrlList;
    }

    public void setImageUrlList(List<String> imageUrlList) {
        this.imageUrlList = imageUrlList;
    }
}